package com.sharer.last.handler;

import cn.hutool.json.JSONUtil;
import com.sharer.last.base.model.R;
import com.sharer.last.model.po.UserPO;
import com.sharer.last.model.vo.TokenResponseVO;
import com.sharer.last.model.vo.user.UserInfoVO;
import com.sharer.last.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录成功处理类
 *
 * @ClassName SecurityAuthenticationSuccessHandler
 * @Author WangJin
 * @Date 2023/05/12/17:11
 * @Description 也可以直接实现AuthenticationSuccessHandler
 * @Version 1.0
 */
@Slf4j
@Component
public class SecurityAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Resource
    RestTemplate restTemplate;

    @Resource
    RedisService redisService;
    /**
     * <h3>登录成功自定义处理逻辑</h3>
     * <p>这里调用在BrowserSecurityConfig类中触发，这是AuthenticationSuccessHandler类的onAuthenticationSuccess方法的实现</p>
     *
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        //更新用户表上次登录时间、更新人、更新时间等字段
        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        UserPO         userDetails     = (UserPO) authentication1.getPrincipal();
        userDetails.setPassword(null);
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String url      = "http://" + request.getServerName() + ":" + request.getServerPort() + "/oauth/token";

//        Map<String, Object> map = new HashMap<>();
//        map.put("grant_type", "password");
//        map.put("username", request.getParameter("username"));
//        map.put("password", request.getParameter("password"));
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);  // 必须该模式，不然请求端无法取到 grant_type
//
//        HttpEntity httpEntity = new HttpEntity<>(headers);

        ResponseEntity<TokenResponseVO> res = restTemplate.getForEntity(url + "?username=" + username + "&password=" + password + "&grant_type=password&client_id=client&scope=read write&client_secret=123456", TokenResponseVO.class);
        // 获取acess_token
        // 返回封装接口
        // TODO 自定义登录成功处理逻辑
//        super.onAuthenticationSuccess(request, response, authentication);//使用默认登录成功逻辑
        UserInfoVO userInfoVO = UserInfoVO.builder().user(userDetails).access_token(res.getBody().getAccess_token()).build();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        redisService.set("access_token",res.getBody().getAccess_token());
        //以json格式对外输出身份信息
        out.write(JSONUtil.toJsonStr(R.ok(userInfoVO)));
        out.flush();
        out.close();

//        if (userDetails == null){
//            //处理编码方式，防止中文乱码的情况
//            response.setContentType("text/json;charset=utf-8");
//            //塞到HttpServletResponse中返回给前台
//            response.getWriter().write(gson.toJson(new ResultInfo<>("接受数据为空")));
//        }else {
//            //处理编码方式，防止中文乱码的情况
//            response.setContentType("text/json;charset=utf-8");
//            //塞到HttpServletResponse中返回给前台
//            Map<String, String> data     = new HashMap<>();
//            String              username = userDetails.getUsername();
//            String              token    = jwtUtil.generate(username);
//            data.put("username" , username);
//            data.put("token", token);
//            //将token的username保存到redis，实现服务端对用户的控制
//            redisUtils.set(username, "token", jwtUtil.expiration, TimeUnit.HOURS);
//            httpServletResponse.getWriter().write(gson.toJson(new ResultInfo<>(data)));
//        }

    }
}
